<template>
  <div class="">
    <!-- 广告组表格展示开始 -->
    <el-card class="box-card" shadow="never">
      <div class="table-box">
        <!-- <cell-header title="广告组"> -->
        <!-- <choose-time class="choose-box" @timeChange="handleTbleTimeChange" /> -->
        <!-- </cell-header> -->
        <table-batch-handle
          v-show="checkedList.length"
          :num="checkedList.length"
          @batchStart="handleBatchStart"
          @batchPause="handleBatchPause"
          @batchDel="handleBatchDel"
        />

        <div v-show="!checkedList.length" class="table-choose-box flex">
          <ul class="set flex">
            <li>
              <span class="title"> 状态 </span>
              <div>
                <el-select
                  v-model="queryData.status"
                  placeholder="请选择"
                  size="small"
                  @change="queryDataChange"
                >
                  <el-option
                    v-for="item in statusOP"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </li>
            <li>
              <div>
                <el-input
                  v-model="queryData.name"
                  size="small"
                  placeholder="搜索广告组"
                  @keyup.enter.native="queryDataChange"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="queryDataChange"
                  />
                </el-input>
              </div>
            </li>
          </ul>

          <div class="handle">
            <em
              v-if="selectBtnShow && campaignInfo.displayStatus !== 'DELETED'"
              @click="addAdGroup"
              >创建广告组</em
            >
            <em @click="thVisible = true">设置显示字段</em>
            <!-- 功能已完成 -->
            <em @click="dowLoadCsv">导出数据</em>
            <!-- 功能已完成 -->
          </div>
        </div>

        <div>
          <el-table
            ref="table"
            v-loading="tableLoading"
            :element-loading-text="tableLoadingtxt"
            :data="tableData"
            style="width: 100%"
            show-summary
            class="series-table"
            sortable="custom"
            :summary-method="returnTotal"
            :header-cell-class-name="headerStyle"
            :row-class-name="setRowClassName"
            @selection-change="tableCheckChange"
            @sort-change="tableSortChange"
          >
            <el-table-column
              v-if="selectBtnShow && campaignInfo.displayStatus !== 'DELETED'"
              type="selection"
              width="45"
              :selectable="
                (row, index) => {
                  return row.displayStatus !== 'DELETED';
                }
              "
            />

            <el-table-column label="广告组名称" width="180" fixed="left">
              <template slot-scope="scope">
                <span style="cursor: pointer" @click="goToGroup(scope.row)">{{
                  scope.row.name
                }}</span>
              </template>
            </el-table-column>

            <el-table-column label="状态" width="200" align="left">
              <template slot-scope="scope">
                <div v-if="scope.row.campaignDisplayStatus === 'ON_HOLD'">
                  <i class="yellow-color status-dot" /> <span>广告系列暂缓</span>
                </div>
                <div v-else>
                  <p v-if="scope.row.displayStatus === 'DELETED'">
                    <span class="pointer"
                      ><i class="del-color status-dot" />已移除</span
                    >
                  </p>

                  <div v-else>
                    <!-- 判断苹果状态 -->
                    <p
                      v-if="scope.row.displayStatus === 'RUNNING'"
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: flex-start;
                      "
                    >
                      <i class="liu-color status-dot" /><span>正在投放</span>
                    </p>

                    <p
                      v-else-if="scope.row.displayStatus === 'PAUSED'"
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: flex-start;
                      "
                    >
                      <i class="yellow-color status-dot" /> <span>已暂停</span>
                    </p>
                    <p
                      v-else-if="scope.row.displayStatus === 'ON_HOLD'"
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: flex-start;
                      "
                    >
                      <i class="yellow-color status-dot" /> <span>广告组暂缓</span>
                    </p>
                    <el-tooltip
                      v-else
                      class="item"
                      effect="dark"
                      placement="top"
                    >
                      <div slot="content">
                        <p
                          v-for="v in scope.row.statusList"
                          style="color: #fff !important"
                        >
                          {{ v }}
                        </p>
                      </div>
                      <p
                        style="
                          display: flex;
                          align-items: center;
                          justify-content: flex-start;
                        "
                        class="pointer"
                      >
                        <i class="yellow-color status-dot" />
                        <span
                          v-if="
                            scope.row.statusList &&
                            scope.row.statusList.length === 1
                          "
                          >{{ scope.row.statusList[0] }}</span
                        >
                        <span v-else>暂停</span>
                      </p>
                    </el-tooltip>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="搜索匹配" width="180">
              <template slot-scope="scope">
                <span
                  v-if="
                    scope.row.automatedKeywordsOptIn &&
                    scope.row.automatedKeywordsOptIn !== 'false'
                  "
                  >开启</span
                >
                <span v-else>关闭</span>
              </template>
            </el-table-column>

            <template v-for="(item, index) in thListCopy1">
              <el-table-column
                v-if="!item.disabled && item.show"
                :key="index"
                :label="item.label"
                :prop="item.prop"
                :sortable="item.sort"
                :width="item.width || 160"
                :align="item.align || 'right'"
              >
                <template slot-scope="scope">
                  <div
                    v-if="
                      item.showSta && campaignInfo.displayStatus !== 'DELETED'
                    "
                    :class="
                      (item.prop === 'defaultBidAmount' ||
                        item.prop === 'bidPerThousand') &&
                      showStatus
                        ? 'price_div'
                        : 'price_no'
                    "
                    @click="openEdit(item.prop, scope.$index)"
                  >
                    <span
                      v-if="
                        item.pre &&
                        !(
                          (item.prop === 'defaultBidAmount' ||
                            item.prop === 'bidPerThousand') &&
                          scope.$index === index_number
                        )
                      "
                    >
                      <span>{{ unitTxt }}</span>
                      <span>{{
                        item.prop === "bidPerThousand"
                          ? scope.row["defaultBidAmount"]
                          : scope.row[item.prop] | $toFixed(2)
                      }}</span>
                    </span>
                    <el-input
                      v-if="
                        (item.prop === 'defaultBidAmount' ||
                          item.prop === 'bidPerThousand') &&
                        scope.$index === index_number
                      "
                      v-model="scope.row.defaultBidAmount"
                      v-focus
                      size="small"
                      @blur="editYS(item.label, scope.$index)"
                      @input="isChange"
                      @keyup.enter.native="editYS(item.label, scope.$index)"
                    ></el-input>
                    <span v-if="item.suf">{{ item.suf }}</span>
                  </div>
                  <div v-else>
                    <span v-if="item.pre">{{ unitTxt }}</span>
                    <span
                      v-if="
                        item.prop === 'taps' ||
                        item.prop === 'installs' ||
                        item.prop === 'impressions' ||
                        item.prop === 'adGroupId' ||
                        item.prop === 'startTime' ||
                        item.prop === 'endTime'
                      "
                    >
                      <template
                        v-if="
                          item.prop !== 'startTime' && item.prop !== 'endTime'
                        "
                        >{{ scope.row[item.prop] }}</template
                      >
                      <template v-else>{{
                        scope.row[item.prop]
                          ? restoreTime(scope.row[item.prop])
                          : "-"
                      }}</template>
                    </span>
                    <span v-else>{{ scope.row[item.prop] | $toFixed(2) }}</span>
                    <span v-if="item.suf">{{ item.suf }}</span>
                  </div>
                  <!-- <span v-if="item.pre">{{ unitTxt }}</span>
                  <span>{{ item.prop==='bidPerThousand'?scope.row['defaultBidAmount']:scope.row[item.prop] }}</span>
                  <span v-if="item.suf">{{ item.suf }}</span> -->
                </template>
              </el-table-column>
            </template>
          </el-table>

          <div
            class="block"
            style="padding-top: 24px; display: flex; justify-content: flex-end"
          >
            <el-pagination
              :current-page="queryData.pageNum"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </el-card>

    <transfer-thead
      :default-th="thList1"
      :th-list="thListCopy1"
      :visible.sync="thVisible"
      @thListChange="handleSubThList"
    />
  </div>
</template>
<script>
import tableBatchHandle from "../../components/table-batch-handle/index.vue";
import cellHeader from "@/components/cell-header.vue";

import transferThead from "../../components/transferThead.vue";

import {
  servingStateReasonsad,
  servingStateReasonscp,
} from "@/utils/servingStateReasons.js";
import { findMaxOne } from "@/api/create.js";
import {
  findReportAdGroupList, // 查询广告系列组下的广告组表格
  findReportAdGroupListTotal, // 总计
  downloadAdGroupCsv, // 下载
  removeAdgroups, // 批量删除
  modifyAdgroups, // 批量更改
} from "@/api/overView.js";

import dayjs from "dayjs";
const moment = dayjs;
var utc = require("dayjs/plugin/utc");
moment.extend(utc);

export default {
  name: "",
  directives: {
    focus: {
      inserted: function (el) {
        el.querySelector("input").focus();
      },
    },
  },
  components: {
    tableBatchHandle,
    cellHeader,
    transferThead,
  }, // ·������
  props: {
    startTime: {
      type: String,
      default: function () {
        return this.$store.state.overview.typeTime.startTime;
      },
    },
    endTime: {
      type: String,
      default: function () {
        return this.$store.state.overview.typeTime.endTime;
      },
    },
    unit: {
      type: String,
      default: function () {
        return this.$store.state.user.unit;
      },
    },
    adchannelType: {
      type: String,
      default: () => {
        return "SEARCH";
      },
    },
    selectBtnShow: {
      type: Boolean,
      default: true,
    },
    campaignInfo: {
      type: Object,
      default: function () {
        const obj = {
          orgId: this.$route.query.orgId || "", // 如果是自助投放为空
          uuid: this.$route.query.uuid || "",
          aId: this.$route.query.aId || this.$route.query.aid || "",
          campaignId: this.$route.query.campaignId,
        };
        const allCa = this.$store.state.overview.allCa;
        const index = allCa.findIndex((item) => {
          return item.campaignId * 1 === obj.campaignId * 1;
        });
        return allCa[index];
      },
    },
  },
  data() {
    return {
      isEdit: false,
      showStatus: true,
      tableLoading: false,
      tableLoadingtxt: "",
      index_number: "",
      price: 0,
      thVisible: false,
      // 表格数据
      // campaign详细数据

      statusOP: [
        {
          // 状态选项
          label: "全部状态",
          value: "",
        },
        {
          label: "正在投放",
          value: "RUNNING",
        },
        {
          label: "已暂停",
          value: "PAUSED",
        },
        {
          label: "广告组暂缓",
          value: "ON_HOLD",
        },
        {
          label: "广告系列暂缓",
          value: "CAMPAIGN_ON_HOLD",
        },
        {
          label: "已移除",
          value: "DELETED",
        },
      ],
      total: 0, // 总条数
      checkedList: [], // 勾选中的数据
      tableData: [], // 表格数据
      tableTotalData: [], // 表格总计数据
      statisticalData: [], // 表格的总计数据
      queryData: {
        // 表格查询参数
        teamId: this.$store.state.team.teamId || "",
        currencyType:
          this.$route.query.currencyType || this.$store.state.user.unit,
        campaignId: this.$route.query.campaignId || "",
        country: "",
        countrySX: this.$store.state.user.timeZone, // 时区
        timeZone: this.$store.getters.timeZoneTime, // 时区比UTC时间少几个小时
        prop: "status", // 选择项
        order: "ascending", // 排序 /descending， ascending
        endTime: this.$store.state.overview.timeObj.overViewTime.endTime, // 结束时间
        startTime: this.$store.state.overview.timeObj.overViewTime.startTime, // 开始时间
        pageNum: 1, // 第多少页；
        pageSize: 10, // 每页多少条
        name: "", // 查询时的名称  模糊查询
        status: "",
        userId: this.$store.state.user.userInfo.userId,
        adChannelType: "", // 投放位置
      },

      thList: [
        {
          prop: "adGroupId", // 属性
          label: "广告组ID", // 名称
          show: false, // 是否显示，
          sort: false, // 是否可以排序
          width: 160,
        },
        {
          prop: "startTime", // 属性
          label: "开始日期", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
          width: 200,
          align: "center",
        },
        {
          prop: "endTime", // 属性
          label: "结束日期", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
          width: 200,
          align: "center",
        },
        {
          prop: "defaultBidAmount", // 属性
          label: "默认最高每次点击费用", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          showSta: true, // 是否可点击
          pre: "$",
          width: 200,
        },
        {
          prop: "bidPerThousand", // 属性
          label: "每千次展示费用出价", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          showSta: true, // 是否可点击
          pre: "$",
          width: 190,
        },

        {
          prop: "localSpendAmount", // 属性
          label: "花费", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          pre: "$",
        },

        {
          prop: "impressions", // 属性
          label: "展示", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "taps", // 属性
          label: "点击", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "installs", // 属性
          label: "安装", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "avgCptAmount", // 属性
          label: "平均每次点击费用", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          pre: "$",
          width: 200,
        },
        {
          prop: "avgCpaAmount", // 属性
          label: "平均每次转化费用", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          pre: "$",
          width: 200,
        },
        {
          prop: "avgCpmAmount", // 属性
          label: "平均每千次展示费用", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          pre: "$",
          width: 200,
        },

        {
          prop: "ttr", // 属性
          label: "点击率", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          suf: "%",
        },
        {
          prop: "conversionRate", // 属性
          label: "转化率", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          suf: "%",
        },
        {
          prop: "newDownloads", // 属性
          label: "新增下载", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "redownloads", // 属性
          label: "重复下载", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "latOffinstalls", // 属性
          label: "关闭LAT下载", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
          width: 200,
        },
        {
          prop: "latOninstalls", // 属性
          label: "开启LAT下载", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
          width: 200,
        },
      ],
      thListCopy: [],
    };
  },
  computed: {
    // 结算币种符号
    unitTxt() {
      if (this.unit === "USD") {
        return "$";
      } else {
        return "￥";
      }
    },
    // 选择的开始时间与结束时间
    timeObj() {
      return this.$store.state.overview.timeObj.overViewTime;
    },
    // 时区
    timeZone() {
      return this.$store.state.user.timeZone;
    },

    thList1() {
      let arr = [];
      if (this.adchannelType === "DISPLAY") {
        // 如果是搜索标签

        arr = this.thList.map((item) => {
          if (item.prop === "defaultBidAmount") {
            return { ...item, disabled: true };
          } else if (item.prop === "avgCptAmount") {
            return { ...item, disabled: true };
          }
          return { ...item, disabled: false };
        });
      } else {
        // 如果是搜索结构

        arr = this.thList.map((item) => {
          if (item.prop === "bidPerThousand") {
            return { ...item, disabled: true };
          } else if (item.prop === "avgCpmAmount") {
            return { ...item, disabled: true };
          }
          return { ...item, disabled: false };
        });
      }
      return arr;
    },

    thListCopy1() {
      if (localStorage.getItem("group-DATA-Thlist")) {
        this.thListCopy = JSON.parse(localStorage.getItem("group-DATA-Thlist"));
      } else {
        this.thListCopy = JSON.parse(JSON.stringify(this.thList));
      }
      let arr = [];
      if (this.adchannelType === "DISPLAY") {
        // 如果是搜索标签
        arr = this.thListCopy.map((item) => {
          if (item.prop === "defaultBidAmount") {
            return { ...item, disabled: true };
          } else if (item.prop === "avgCptAmount") {
            return { ...item, disabled: true };
          }
          return { ...item, disabled: false };
        });
      } else {
        // 如果是搜索结果
        arr = this.thListCopy.map((item) => {
          if (item.prop === "bidPerThousand") {
            return { ...item, disabled: true };
          } else if (item.prop === "avgCpmAmount") {
            return { ...item, disabled: true };
          }
          return { ...item, disabled: false };
        });
      }

      return arr;
    },
  },
  watch: {
    timeZone: {
      // �����Ķ���
      deep: true, // ���ȼ�������Ϊ true
      handler: function (newV, oldV) {
        this.queryData.pageNum = 1;
        this.queryData.countrySX = this.$store.state.user.timeZone; // 时区
        this.queryData.timeZone = this.$store.getters.timeZoneTime;
        this.findReportAdGroupList();
        this.findReportAdGroupListTotal();
      },
    },
    timeObj: {
      // �����Ķ���
      deep: true, // ���ȼ�������Ϊ true
      handler: function (newV, oldV) {
        this.queryData.startTime = newV.startTime;
        this.queryData.endTime = newV.endTime;
        this.queryData.pageNum = 1;
        if (!this.$route.query.campaignId && !this.$route.query.campaignid)
          return false;
        this.findReportAdGroupList();
        this.findReportAdGroupListTotal();
      },
    },
    tableData(newV) {
      this.tableData = newV;
    },
  },
  // ������
  created() {},
  // ���غ�
  mounted() {
    this.findReportAdGroupList();
    this.findReportAdGroupListTotal();
  },
  // ���ٺ�
  destroyed() {},

  // ����
  methods: {
    setRowClassName(data) {
      if (data.row.displayStatus === "DELETED") {
        return "del-row";
      } else {
        return "";
      }
    },

    restoreTime(time) {
      // console.log(time, '还原时间')
      if (this.timeZone === "UTC") {
        return moment(time).format("YYYY-MM-DD");
      } else {
        return moment(time).add(8, "hour").format("YYYY-MM-DD");
      }
    },

    // 查询广告系列状态值
    findServingStateReasonscp(type) {
      const arr = servingStateReasonscp(type);
      return arr;
    },

    headerStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        return "center-align";
      }
    },

    async findMaxOne() {
      const obj = {
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
        campaignId: this.tableData[this.index_number].campaignId,
        currencyType: this.$store.state.user.unit,
        teamId: this.$store.state.team.teamId || "",
      };
      const res = await findMaxOne(obj);
      this.price = res.data.data * 1;
    },
    isChange(value) {
      if (value) {
        this.isEdit = true;
      }
    },
    editYS(name, index) {
      this.showStatus = true;
      // return console.log(this.campaignInfo.dailyBudgetAmount, this.tableData[index].defaultBidAmount, this.campaignInfo.budgetAmount)
      if (!this.isEdit) {
        return (this.index_number = -1);
      } else if (this.tableData[index].defaultBidAmount * 100 < 1) {
        this.$message.error(`你的${name}必须至少为0.01`);
        this.findReportAdGroupList();
        this.isEdit = false;
        this.index_number = -1;
      } else if (
        this.campaignInfo.dailyBudgetAmount !== null &&
        this.campaignInfo.dailyBudgetAmount !== undefined &&
        this.tableData[index].defaultBidAmount * 1 >
          this.campaignInfo.dailyBudgetAmount * 1
      ) {
        this.index_number = -1;
        this.$message.error(
          `你的${name}必须至少为0.01 且不得超过广告系列每日预算`
        );
        this.findReportAdGroupList();
        this.isEdit = false;
      } else if (this.campaignInfo.budgetAmount) {
        if (
          this.tableData[index].defaultBidAmount * 1 >
            this.campaignInfo.budgetAmount * 1 ||
          this.tableData[index].defaultBidAmount * 100 < 1
        ) {
          this.index_number = -1;
          this.$message.error(
            `你的${name}必须至少为0.01 且不得超过广告系列预算`
          );
          this.findReportAdGroupList();
          this.isEdit = false;
        }
      } else if (this.price * 1 > this.tableData[index].defaultBidAmount * 1) {
        this.index_number = -1;
        this.$message.error(
          `${name}不能低于该广告系列的关键词/单次点击费用最高价`
        );
        this.findReportAdGroupList();
        this.isEdit = false;
      } else {
        const arr = [];
        arr.push({
          teamId: this.$store.state.team.teamId || "",
          currencyType:
            this.$route.query.currencyType || this.$store.state.user.unit,
          campaignId: this.$route.query.campaignId,
          orgId: this.$route.query.orgId || "", // 如果是自助投放为空
          uuid: this.$route.query.uuid || "",
          aId: this.$route.query.aId || this.$route.query.aid || "",
          userId: this.$store.state.user.userInfo.userId,
          adGroupId: this.tableData[index].adGroupId,
          adGroupUpdate: {
            defaultBidAmountNub: this.tableData[index].defaultBidAmount,
          },
        });
        this.modifyAdgroups(arr);
      }
    },
    // 打开编辑框
    openEdit(name, index) {
      this.index_number = index;
      if (name === "defaultBidAmount" || name === "bidPerThousand") {
        if (this.campaignInfo.adChannelType === "SEARCH") {
          this.findMaxOne();
        } else {
          this.price = 0;
        }
        this.tableData.forEach((item, i) => {
          if (index === i) {
            this.showStatus = false;
          }
        });
      }
    },
    // 去广告组详情
    goToGroup(data) {
      const query = {
        ...this.$route.query,
        adGroupId: data.adGroupId,
        adchannelType: this.campaignInfo.adchannelType,
        adStatus: data.displayStatus,
      };
      this.$router.push({
        name: "groupOverview",
        query,
      });
    },
    // 表格变化
    // 表格勾选
    tableCheckChange(data) {
      this.checkedList = JSON.parse(JSON.stringify(data));
    },

    // 搜索选项变化
    queryDataChange() {
      this.$nextTick(() => {
        this.queryData.pageNum = 1;
        this.findReportAdGroupList();
        this.findReportAdGroupListTotal();
      });
    },
    // 每页多少条
    handleSizeChange(index) {
      this.queryData.pageSize = index;
      this.findReportAdGroupList();
      this.findReportAdGroupListTotal(); // 查询总计数据
    },
    // 页数
    handleCurrentChange(index) {
      this.queryData.pageNum = index;
      this.findReportAdGroupList();
      this.findReportAdGroupListTotal(); // 查询总计数据
    },

    // 排序变化
    tableSortChange(obj) {
      if (!obj.order) {
        this.queryData.prop = "status";
        this.queryData.order = "descending";
      } else {
        this.queryData.prop =
          obj.prop === "bidPerThousand" ? "defaultBidAmount" : obj.prop;
        this.queryData.order = obj.order;
      }
      this.queryData.pageNum = 1;
      this.findReportAdGroupList();
      this.findReportAdGroupListTotal(); // 查询总计数据
    },

    // 下载表格数据
    async dowLoadCsv() {
      if (!this.tableData.length) {
        this.$message.closeAll();
        this.$message.error("请先创建广告组");
        return false;
      }

      const res = await downloadAdGroupCsv({
        ...this.queryData,
        pageNum: 1,
        pageSize: this.total,
        teamId: this.$store.state.team.teamId || "",
        startTime: this.startTime,
        endTime: this.endTime,
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
      });
      if (!res.data.message) {
        const blob = new Blob(["\ufeff" + res.data], {
          type: "text/csv,charset=UTF-8",
        });
        const that = this;
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.setAttribute("href", objectUrl);
        a.setAttribute(
          "download",
          "YYY_DATA_竞价计划列表_广告组" +
            that.queryData.startTime +
            "_" +
            this.queryData.endTime +
            ".csv"
        );
        a.click();
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "服务器错误，请稍后重试");
      }
    },

    // 获取表格数据
    async findReportAdGroupList() {
      this.tableLoading = true;
      this.tableLoadingtxt = "获取最新数据中,请稍候";
      const res = await findReportAdGroupList({
        ...this.queryData,
        teamId: this.$store.state.team.teamId || "",
        startTime: this.startTime,
        endTime: this.endTime,
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
      });
      this.tableLoading = false;
      if (res.data.code === 20000) {
        const arr = res.data.data.list.map((item) => {
          if (item.servingStateReasons && item.servingStateReasons.length) {
            const statusList = servingStateReasonsad(item.servingStateReasons);
            item.statusList = statusList;
          }
          if (
            item.avgCpmAmount &&
            item.avgCpmAmount !== null &&
            item.avgCpmAmount !== undefined
          ) {
            item.avgCpmAmount = item.avgCpmAmount * 1;
          }
          if (
            item.cpaGoalAmount &&
            item.cpaGoalAmount !== null &&
            item.cpaGoalAmount !== undefined
          ) {
            item.cpaGoalAmount = item.cpaGoalAmount * 1;
          }
          if (
            item.defaultBidAmount &&
            item.defaultBidAmount !== null &&
            item.defaultBidAmount !== undefined
          ) {
            item.defaultBidAmount = item.defaultBidAmount * 1;
          }
          item.localSpendAmount = item.localSpendAmount * 1;
          item.avgCpaAmount = item.avgCpaAmount * 1;
          item.avgCptAmount = item.avgCptAmount * 1;
          return item;
        });
        this.tableData = arr;
        this.total = res.data.data.total;
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "服务器错误，请稍后重试");
      }
    },

    // 获取表格总计数据
    async findReportAdGroupListTotal() {
      const res = await findReportAdGroupListTotal({
        ...this.queryData,
        teamId: this.$store.state.team.teamId || "",
        startTime: this.startTime,
        endTime: this.endTime,
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
      });

      if (res.data.code && res.data.code === 20000) {
        this.tableTotalData = res.data.data[0];
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "服务器错误，请稍后重试");
      }
    },

    returnTotal(param) {
      const {
        columns,
        // data
      } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "总计";
          return;
        } else {
          for (const key in this.tableTotalData) {
            if (key === column.property) {
              switch (key) {
                case "localSpendAmount":
                  sums[index] =
                    this.unitTxt + (this.tableTotalData[key] * 1).toFixed(2);
                  break;
                case "avgCpaAmount":
                  sums[index] =
                    this.unitTxt + (this.tableTotalData[key] * 1).toFixed(2);
                  break;
                case "avgCptAmount":
                  sums[index] =
                    this.unitTxt + (this.tableTotalData[key] * 1).toFixed(2);
                  break;
                case "ttr":
                  sums[index] = (this.tableTotalData[key] * 1).toFixed(2) + "%";
                  break;
                case "conversionRate":
                  sums[index] = this.tableTotalData[key].toFixed(2) + "%";
                  break;

                default:
                  sums[index] = this.tableTotalData[key];
                  break;
              }
            }
          }
        }
      });

      return sums;
    },

    async handleBatchStart() {
      this.tableLoading = true;
      this.tableLoadingtxt = "数据修改中,请稍候";
      const arr = this.checkedList.map((item) => {
        const obj = {
          teamId: this.$store.state.team.teamId || "",
          currencyType:
            this.$route.query.currencyType || this.$store.state.user.unit,
          campaignId: this.$route.query.campaignId,
          orgId: this.$route.query.orgId || "", // 如果是自助投放为空
          uuid: this.$route.query.uuid || "",
          aId: this.$route.query.aId || this.$route.query.aid || "",
          aId: this.$route.query.aId || this.$route.query.aid || "",
          userId: this.$store.state.user.userInfo.userId,
          adGroupId: item.adGroupId,
          adGroupUpdate: {
            status: "ENABLED",
          },
        };
        return obj;
      });
      this.modifyAdgroups(arr);
    },
    // 公共修改方法
    async modifyAdgroups(data) {
      this.index_number = -1;
      this.isEdit = false;
      const res = await modifyAdgroups(data);
      if (res.data.code && res.data.code === 20000) {
        // this.$message.closeAll()
        // this.$message({
        //   type: 'success',
        //   message: res.data.message || '操作成功'
        // })
        this.tableLoading = true;
        this.tableLoadingtxt = "数据更新中,请稍候";
        setTimeout(() => {
          this.findReportAdGroupList();
          this.findReportAdGroupListTotal();
        }, 3000);
      } else {
        this.$message.closeAll();
        this.tableLoading = false;
        this.$message.error(res.data.message || "服务器错误，请稍后重试");
      }
    },
    // 批量暂停
    async handleBatchPause() {
      this.tableLoading = true;
      this.tableLoadingtxt = "数据更改中，请稍候";
      const arr = this.checkedList.map((item) => {
        const obj = {
          teamId: this.$store.state.team.teamId || "",
          currencyType:
            this.$route.query.currencyType || this.$store.state.user.unit,
          campaignId: this.$route.query.campaignId,
          orgId: this.$route.query.orgId || "", // 如果是自助投放为空
          uuid: this.$route.query.uuid || "",
          aId: this.$route.query.aId || this.$route.query.aid || "",
          aId: this.$route.query.aId || this.$route.query.aid || "",
          userId: this.$store.state.user.userInfo.userId,
          adGroupId: item.adGroupId,
          adGroupUpdate: {
            status: "PAUSED",
          },
        };
        return obj;
      });

      this.modifyAdgroups(arr);
    },

    // 批量删除
    async handleBatchDel() {
      this.tableLoading = true;
      this.tableLoadingtxt = "数据删除中,请稍候";
      const arr = this.checkedList.map((item) => {
        const obj = {
          teamId: this.$store.state.team.teamId || "",
          currencyType:
            this.$route.query.currencyType || this.$store.state.user.unit,
          adGroupId: item.adGroupId,
          orgId: this.$route.query.orgId || "", // 如果是自助投放为空
          uuid: this.$route.query.uuid || "",
          aId: this.$route.query.aId || this.$route.query.aid || "",
          userId: this.$store.state.user.userInfo.userId,
          campaignId: this.$route.query.campaignId * 1,
        };
        return obj;
      });

      const res = await removeAdgroups(arr);

      if (res.data.code && res.data.code === 20000) {
        this.$message.closeAll();
        this.$message({
          type: "success",
          message: res.data.message || "数据删除中,请稍候",
        });

        this.tableLoadingtxt = "数据更新中,请稍候";
        setTimeout(() => {
          this.queryData.pageNum = 1;
          this.findReportAdGroupList();
          this.findReportAdGroupListTotal();
          this.$emit("delAd");

          this.$store.dispatch("overview/getAllCampaign", {
            currencyType: this.$store.state.user.unit,
            appid: "", // 当前需求 写死 为空
            userId: this.$store.state.user.userInfo.userId,
            orgId: this.$route.query.orgId || "", // 如果是自助投放为空
            uuid: this.$route.query.uuid || "",
            aId: this.$route.query.aId || this.$route.query.aid || "",
            teamId: this.$store.state.team.teamId,
            campaignGroupId:
              this.$route.query.serialId || this.$route.query.serialid || "",
          });
          this.$store.dispatch("overview/getAllAdgroup", {
            campaignId:
              this.$route.query.campaignId ||
              this.$route.query.campaignid ||
              "",
            currencyType: this.$store.state.user.unit,
            appid: "", // 当前需求 写死 为空
            userId: this.$store.state.user.userInfo.userId,
            orgId: this.$route.query.orgId || "", // 如果是自助投放为空
            uuid: this.$route.query.uuid || "",
            aId: this.$route.query.aId || this.$route.query.aid || "",
            teamId: this.$store.state.team.teamId,
            campaignGroupId:
              this.$route.query.serialId || this.$route.query.serialid || "",
          });
        }, 1500);
      } else {
        this.$message.closeAll();
        this.$message.error({
          message: res.data.message || "服务器发生错误，请重试",
        });
      }
    },

    // 去创建广告组
    addAdGroup() {
      localStorage.setItem(
        "series-DATA",
        JSON.stringify({
          campaignForm: this.campaignInfo,
        })
      );

      this.$router.push({
        name: "CreateGroup", // 去创建广告组
        query: {
          create: "addGroup",
          // type: 'self-help',
          type: "common",
          campaignId: this.$route.query.campaignId,
          uuid: this.$route.query.uuid || "",
          orgid: this.$route.query.orgId || this.$route.query.orgId || "",
          serialId:
            this.$route.query.serialId || this.$route.query.serialid || "",
        },
      });
    },

    // 储存修改后的显示字段
    handleSubThList(data) {
      this.thListCopy = JSON.parse(JSON.stringify(data));
      localStorage.setItem("group-DATA-Thlist", JSON.stringify(data));
      this.$refs["table"].doLayout();
      this.$forceUpdate();
    },
  },
};
</script>

<style lang="scss" scoped="true">
@import "../../components/handle.scss";
@import "~@/styles/variables.scss";

.price_div {
  padding: 2px;
  cursor: pointer;
  border-radius: 2px;
}

.price_div:hover {
  border: 1px solid #e0e2e7;
  border-radius: 2px;
}

.data {
  padding-bottom: 24px;
}

.trend-card {
  margin-bottom: 24px;
}

.table-box {
  .series-table {
    margin-top: 24px;

    /deep/ thead {
      th.el-table__cell.is-right > .cell {
        padding-left: 10px !important;
        padding-right: 24px;

        .caret-wrapper {
          position: absolute;
          top: 50%;
          right: 0;
          transform: translateY(-46%);
        }
      }
    }

    /deep/ .el-table__body {
      background: #ffffff;

      .el-table__cell.is-right > .cell {
        padding-right: 24px;
      }
    }

    /deep/ .el-table__footer-wrapper .el-table__cell.is-right > .cell {
      padding-right: 24px;
    }

    /deep/ .del-row {
      background: rgba(57, 68, 78, 0.1);

      td,
      .cell {
        background: transparent !important;
      }
    }
  }
}
</style>
